<template>
  <div v-loading="loading" align="center">
    <div v-show="project.items.length > 0">
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form ref="refProjectCom" class="gl_form_mini" :model="project.competive" label-width="110px">
            <el-form-item
              :label="`${project.competive.name}`"
              prop="point"
              size="mini"
              :rules="[
                { required: true, message: `${project.competive.name}不能为空`, trigger: 'blur' },
                { pattern: /^\+?(:?(:?\d+\.\d+)|(:?\d+))$/, message: '积分只能为非负数'}
              ]"
            >
              <el-input v-model="project.competive.point" clearable :placeholder="`请输入${project.competive.name}`" />
            </el-form-item>
          </el-form>
          <el-form ref="refProjectNoneCom" class="gl_form_mini" :model="project.noneCompetive" label-width="110px">
            <el-form-item
              :label="`${project.noneCompetive.name}`"
              prop="point"
              size="mini"
              :rules="[
                { required: true, message: `${project.noneCompetive.name}不能为空`, trigger: 'blur' },
                { pattern: /^\+?(:?(:?\d+\.\d+)|(:?\d+))$/, message: '积分只能为非负数'}
              ]"
            >
              <el-input v-model="project.noneCompetive.point" clearable :placeholder="`请输入${project.noneCompetive.name}`" />
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col align="center" :span="22">
          <el-tabs v-model="categoryId" tab-position="top" class="gl_mt_10" @tab-click="handleClick">
            <el-tab-pane v-for="(item, index) in project.items" :key="item.categoryId" :label="item.categoryName" :name="item.categoryId">
              <div slot="label">
                <div slot="reference" :title="item.categoryName" style="width: 154px;" class="gl_ellipsis">{{ item.categoryName }}</div>
              </div>
              <el-form :ref="`ref${item.categoryName + index}`" class="gl_form_mini" :model="item.settings" label-width="110px">
                <el-row :gutter="40">
                  <el-col v-for="(jtem, key, jndex) in item.settings" :key="jndex" :span="13">
                    <el-form-item
                      :key="jndex"
                      :label="`${jtem.name}`"
                      :prop="`.${key}.point`"
                      size="mini"
                      :rules="[
                        { required: true, message: `${jtem.name}的积分不能为空`, trigger: 'blur' },
                        { pattern: /^\+?(:?(:?\d+\.\d+)|(:?\d+))$/, message: '积分只能为非负数'}
                      ]"
                    >
                      <el-input v-model="jtem.point" clearable :placeholder="`请输入${jtem.name}的积分`" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
              <el-button type="primary" size="mini" :loading="submitLoading" style="width: 120px; margin-top: 30px" @click="handleSubmitTeamScore(index)">提交</el-button>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </div>
    <div v-show="!project.items.length > 0" style="line-height: 400px" class="gl_noData_mockTable">
      <p>
        <span>请创建项目后，再进行项目方式的积分设置</span>
      </p>
    </div>
  </div>
</template>
<script>
import {
  api_PUT_EventsManagementPointSetting, // 新建或更新赛事积分
  api_GET_EventsManagementPointSetting // 获取赛事积分列表
} from '@/extend/api/gameswaggerApi/app';
export default {
  name: 'IntegralSetting',
  data() {
    return {
      project: {
        competive: {},
        noneCompetive: {},
        items: []
      },
      submitPointSettingInput: {},
      loading: false,
      submitLoading: false,
      categoryId: ''
    };
  },
  created() {
    this.getPointSetting();
  },
  methods: {
    handleClick(tab) {
      this.$refs[`ref${tab.label + tab.index}`][0].clearValidate();
    },
    // 获取积分设置
    getPointSetting() {
      this.loading = true;
      api_GET_EventsManagementPointSetting({ CompetitionId: this.$route.params.id }).then(res => {
        this.processDisplayData(res);
        this.loading = false;
      }, error => {
        this.$message({ type: 'error', message: error.error && error.error.message });
        this.loading = false;
      });
    },
    // 提交 —— 积分设置
    handleSubmitTeamScore(key) {
      const _this = this;
      _this.submitLoading = true;
      var _comValidate = null;
      var _noneComValidate = null;
      _this.$refs['refProjectCom'].validate(valid => {
        if (valid) {
          _comValidate = true;
        } else {
          _comValidate = false;
        }
      });
      _this.$refs['refProjectNoneCom'].validate(valid => {
        if (valid) {
          _noneComValidate = true;
        } else {
          _noneComValidate = false;
        }
      });
      // 项目方式会存在多个，所以需要循环配置出来
      const _categoryScore = _this.project.items.map((item, index) => {
        var _validate = null;
        _this.$refs[`ref${item.categoryName + index}`][0].validate(valid => {
          if (valid) {
            _validate = true;
          } else {
            _validate = false;
          }
        });
        return {
          validate: _validate,
          name: item.categoryName
        };
      });
      if (_comValidate && _noneComValidate && _categoryScore[key].validate) {
        _this.submitPointSettingInput = {
          competive: {},
          noneCompetive: {},
          items: []
        };
        const _form = JSON.parse(JSON.stringify(_this.project));
        _this.submitPointSettingInput.competive = _form.competive;
        _this.submitPointSettingInput.noneCompetive = _form.noneCompetive;
        _this.submitPointSettingInput.items = [_form.items[key]];
        const category = JSON.parse(JSON.stringify(_form.items[key]));
        _this.submitPointSettingInput.items[0].settings = [];
        for (const k in category.settings) {
          _this.submitPointSettingInput.items[0].settings.push(category.settings[k]);
        }
        api_PUT_EventsManagementPointSetting({ category: _this.submitPointSettingInput }).then(res => {
          _this.submitLoading = false;
          _this.project = {
            competive: {},
            noneCompetive: {},
            items: []
          };
          _this.submitPointSettingInput = {};
          // 编辑成功再获取数据做回显
          _this.getPointSetting();
          _this.$message({ type: 'success', message: '操作成功！' });
        }, error => {
          _this.submitLoading = false;
          _this.submitPointSettingInput = {};
          _this.$message({ type: 'error', message: error.error && error.error.message });
        });
      } else {
        _this.$message({ type: 'error', duration: 4000, message: '请检查参与分及该项目的各个积分是否都已填写完毕' });
        _this.submitLoading = false;
      }
    },
    processDisplayData(res) {
      const _this = this;
      _this.project.competive = res.category.competive;
      _this.project.noneCompetive = res.category.noneCompetive;
      _this.project.items = res.category.items;
      const category = JSON.parse(JSON.stringify(res.category.items));
      _this.categoryId = category.length > 0 ? category[0].categoryId : '';
      for (let j = 0; j < category.length; j++) {
        const jtem = category[j].settings;
        _this.project.items[j].settings = {};
        for (let k = 0; k < jtem.length; k++) {
          const ktem = jtem[k];
          _this.$set(_this.project.items[j].settings, k, ktem);
        }
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.el-tabs__header {
  .el-tabs__item {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>
